package server;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Set;

import message.Response;
import message.response.ListResponse;
import util.Config;

public class FileServer {

	private String directoryPath;
	private int tcpPort;
	private String proxyHost;
	private int proxyUdpPort;
	private int alivePeriod;

	private File directory;
	private Config config;
	
	private Map<String, Integer> fileVersions;

	public FileServer(Config config) throws MissingResourceException {

		this.config = config;
		directoryPath = config.getString("fileserver.dir");
		tcpPort = config.getInt("tcp.port");
		proxyHost = config.getString("proxy.host");
		proxyUdpPort = config.getInt("proxy.udp.port");
		alivePeriod = config.getInt("fileserver.alive");

		fileVersions = Collections
				.synchronizedMap(new HashMap<String, Integer>());
		directory = new File(this.directoryPath);
	}
	
	public Config getConfig() {
		return config;
	}

	public int getTcpPort() {
		return tcpPort;
	}

	public String getProxyHost() {
		return proxyHost;
	}

	public int getProxyUdpPort() {
		return proxyUdpPort;
	}

	public int getAlivePeriod() {
		return alivePeriod;
	}

	public File getDirectory() {
		return directory;
	}
	
	private void refreshFileList() {
		String fileName = null;

		for (File file : getDirectory().listFiles()) {
			fileName = file.getName();
			//search for versions if no version data was found, save as version 1
			if(fileVersions.get(fileName) == null)
				fileVersions.put(fileName, 1);
		}
	}
	
	public Set<String> getFileList() {
		refreshFileList();
		return fileVersions.keySet();
	}
	
	public Response versionList() throws IOException {
		refreshFileList();
		Set<String> allFileNames = new HashSet<String>();
		
		for(String filename : fileVersions.keySet())
			allFileNames.add(filename + " (v. " + fileVersions.get(filename) + ")");
		
		return new ListResponse(allFileNames);
	}

	public Map<String, Integer> getFileVersions() {
		return fileVersions;
	}

	public String getAliveMessage() {
		return "!alive " + tcpPort;
	}
}
